<?php
// 启动会话
session_start();

// 检查是否已登录
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

// 检查是否为POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
    exit;
}

// 引入数据库配置
require_once '../config.php';

// 获取POST数据
$currentPassword = $_POST['current_password'] ?? '';
$newPassword = $_POST['new_password'] ?? '';

// 验证输入
if (empty($currentPassword) || empty($newPassword)) {
    echo json_encode(['success' => false, 'message' => '请填写所有字段']);
    exit;
}

if (strlen($newPassword) < 6) {
    echo json_encode(['success' => false, 'message' => '新密码长度至少为6个字符']);
    exit;
}

// 获取当前管理员信息
$adminId = $_SESSION['admin_id'];
$stmt = $pdo->prepare("SELECT password FROM admins WHERE id = :id");
$stmt->bindParam(':id', $adminId, PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch();

if (!$admin) {
    echo json_encode(['success' => false, 'message' => '管理员不存在']);
    exit;
}

// 验证当前密码
if (!password_verify($currentPassword, $admin['password'])) {
    echo json_encode(['success' => false, 'message' => '当前密码不正确']);
    exit;
}

// 加密新密码
$newHashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

// 更新密码
$stmt = $pdo->prepare("UPDATE admins SET password = :password WHERE id = :id");
$stmt->bindParam(':password', $newHashedPassword, PDO::PARAM_STR);
$stmt->bindParam(':id', $adminId, PDO::PARAM_INT);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => '密码修改成功！']);
} else {
    echo json_encode(['success' => false, 'message' => '密码修改失败，请稍后再试']);
}

$stmt = null;
?>